package com.gitee.zzh.common;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 配置文件工具
 */
public class ConfigUtil {
	private static final String CONFIG_DIR = "config";
	private static final String CONFIG_META_FILE = "/FileCodeGenerator.json";
	private static final String DRIVER = "org.sqlite.JDBC";
	private static final String DB_URL = "jdbc:sqlite:./config/ConfigDB.db";
	private static final String TEMPLATE_DIR = "template";
	private final static Logger LOG = Logger.getLogger(ConfigUtil.class);

	/**
	 * 获得数据库连接
	 */
	public static Connection getConnection() {
        try {
            Class.forName(DRIVER);
			return DriverManager.getConnection(DB_URL);
		} catch (ClassNotFoundException | SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public static void createConfigFile() {
		File path = new File(CONFIG_DIR);
		if (!path.exists()) {
			System.out.println("createConfigDir : " + path.mkdir());
		}
        try {
			URL resource = Thread.currentThread().getContextClassLoader().getResource(CONFIG_DIR);
			URI uri = resource.toURI();
			Files.list(Paths.get(uri)).forEach(x -> {
				Path out = Paths.get(CONFIG_DIR, x.getFileName().toString());
				try {
					if(!new File(out.toString()).exists()) {
						Files.copy(x, out);
					}
				} catch (IOException e) {
					AlertUtil.showErrorAlert("创建模板-->失败:" + e);
				}
			});
        } catch (IOException | URISyntaxException e) {
            throw new RuntimeException(e);
        }
	}

	/**
	 * 查看是否存在模板文件夹,如果不存在则创建
	 */
	public static void createTemplate() {
		Path path = Paths.get(TEMPLATE_DIR);
		try {
			if (Files.notExists(path)) {
				LOG.debug("执行创建模板...");
				Files.createDirectory(path);
			}
			URL resource = Thread.currentThread().getContextClassLoader().getResource(TEMPLATE_DIR);
			URLConnection conn = resource.openConnection();
			if (conn instanceof JarURLConnection) {
				LOG.debug("jar");
				jarCreateTemplate((JarURLConnection) conn);
			} else {
				URI uri = resource.toURI();
				Files.list(Paths.get(uri)).forEach(x -> {
					Path out = Paths.get(TEMPLATE_DIR, x.getFileName().toString());
					try {
						if (!Files.exists(out)) {
							Files.copy(x, out);
						}
					} catch (IOException e) {
						LOG.debug("创建模板-->失败:" + e);
						AlertUtil.showErrorAlert("创建模板-->失败:" + e);
					}
				});
			}
		} catch (Exception e) {
			LOG.debug("创建模板-->失败:" + e);
			AlertUtil.showErrorAlert("创建模板-->失败:" + e);
		}
	}

	/**
	 * 将jar里面的文件复制到模板文件夹
	 */
	public static void jarCreateTemplate(JarURLConnection jarConn) throws IOException {
		try (JarFile jarFile = jarConn.getJarFile()) {
			Enumeration<JarEntry> entrys = jarFile.entries();
			while (entrys.hasMoreElements()) {
				JarEntry entry = entrys.nextElement();
				if (entry.getName().startsWith(jarConn.getEntryName()) && !entry.getName().endsWith("/")) {
					String fileName = entry.getName().replace(TEMPLATE_DIR + "/", "");
					InputStream inpt = Thread.currentThread().getContextClassLoader().getResourceAsStream(entry.getName());
					Files.copy(inpt, Paths.get(TEMPLATE_DIR, fileName));
				}
			}
		} catch (Exception e) {
			LOG.debug("从jar包创建模板-->失败:" + e);
			AlertUtil.showErrorAlert("从jar包创建模板-->失败:" + e);
		}
	}

	public static String getConfigFileContent() {
		File file = new File(CONFIG_DIR + CONFIG_META_FILE);
        try {
            return Files.readString(file.toPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

	/**
	 * 保存数据库连接
	 */
	public static void saveDatabaseConfig(String connName, DatabaseConfig dbConfig) {
        try (Connection conn = getConnection();
			Statement stat = conn.createStatement()){
			ResultSet rs1 = stat.executeQuery(String.format("select * from DBSet where name ='%s'", connName));
			if (rs1.next()) {
				throw new RuntimeException("该连接名称已经存在!请使用其它名字...");
			}
			String jsonStr = JSON.toJSONString(dbConfig);
			String sql = String.format("insert into DBSet values('%s', '%s')", connName, jsonStr);
			stat.executeUpdate(sql);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 更新数据库连接
	 */
	public static void updateDatabaseConfig(DatabaseConfig dbConfig) {
        try (Connection conn = getConnection();
			Statement stat = conn.createStatement()){
			String jsonStr = JSON.toJSONString(dbConfig);
			String sql = String.format("update DBSet set value='%s' where name='%s'", jsonStr, dbConfig.getConnName());
			stat.executeUpdate(sql);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获得数据库连接
	 */
	public static List<DatabaseConfig> getDatabaseConfig() {
        try (Connection conn = getConnection();
			Statement stat = conn.createStatement()){
			ResultSet rs = stat.executeQuery("select * from DBSet");
			List<DatabaseConfig> result = new ArrayList<DatabaseConfig>();
			while (rs.next()) {
				String name = rs.getString("name");
				String value = rs.getString("value");
				DatabaseConfig databaseConfig = JSON.parseObject(value, DatabaseConfig.class);
				databaseConfig.setConnName(name);
				result.add(databaseConfig);
			}
			return result;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
    }

	/**
	 * 删除数据库连接
	 */
	public static void deleteDatabaseConfig(String name) {
		try (Connection conn = getConnection();
			Statement stat = conn.createStatement()){
			String sql = String.format("delete from DBSet where name='%s'", name);
			stat.executeUpdate(sql);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
